import { APP_BASE_API } from "@/config";
import { handleMockRequest, mockSwitch } from "./mock/index";

let runtimeMockFlag = null;

export function isMockEnabled() {
  if (runtimeMockFlag === null) {
    runtimeMockFlag = mockSwitch.isEnabled();
  }
  return runtimeMockFlag;
}

export function setMockEnabled(flag) {
  runtimeMockFlag = mockSwitch.setEnabled(flag);
}

export function request(options = {}) {
  const {
    url = "",
    method = "GET",
    data = {},
    header = {},
    mock
  } = options;

  const useMock = typeof mock === "boolean" ? mock : isMockEnabled();
  if (!url) {
    return Promise.reject(new Error("请求 URL 不能为空"));
  }

  if (useMock) {
    return handleMockRequest({ url, method, data });
  }

  const finalUrl = normalizeUrl(url);
  const finalMethod = method.toUpperCase();

  return new Promise((resolve, reject) => {
    uni.request({
      url: finalUrl,
      data,
      method: finalMethod,
      header: {
        "Content-Type": "application/json",
        ...header
      },
      success: ({ statusCode, data: responseData }) => {
        if (statusCode === 200) {
          resolve(responseData);
        } else {
          reject(new Error(`网络错误(${statusCode})`));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

function normalizeUrl(path) {
  if (/^https?:\/\//i.test(path)) {
    return path;
  }
  const base = APP_BASE_API || "";
  if (path.startsWith("/")) {
    return `${base}${path}`;
  }
  return `${base}/${path}`;
}
